package dao

import (
	"gorm.io/gorm"
	"wish_go/src/main/com/ajie/common"
	"wish_go/src/main/com/ajie/model"
	"wish_go/src/main/com/ajie/vo"
)

func PageUser(params *vo.UserVo) (rows []model.User, total int64, err error) {
	// 分页查询
	offset := (params.PageInfo.Page - 1) * params.PageInfo.PageSize
	db := common.GetDB()
	tx := db.Model(&model.User{})
	if len(params.PageInfo.Keywords) > 0 {
		tx.Where("(nick_name like ? or phonenumber like ?)", params.PageInfo.Keywords, params.PageInfo.Keywords)
	}
	// 预留字段查询具体社区
	if len(params.User.AreaCode) > 0 {
		if params.User.Role == 4 {
			params.User.AreaCode = params.User.AreaCode[0:4]
		}
		tx.Where("area_code in (?)", db.Model(&model.Area{}).Select("area_code").Where("area_code like ?", params.User.AreaCode+"%"))
	}
	err = tx.Count(&total).Limit(params.PageInfo.PageSize).Offset(offset).Order(params.PageInfo.SortName).Find(&rows).Error
	return
}

func InsertMini(user model.User) (dbErr error) {
	db := common.GetDB()
	// 查询用户是否存在
	getUser, userErr := GetUser(db, user)
	if userErr != nil {
		return userErr
	}
	if getUser.Id == 0 {
		dbErr = db.Create(&user).Error
	}
	return
}

func UpdateMiniUser(user model.User) (i int64, dbErr error) {
	db := common.GetDB()
	updates := db.Model(model.User{}).Where("openid = ?", user.Openid).Updates(user)
	i = updates.RowsAffected
	dbErr = updates.Error
	return
}

// GetUser 根据用户名查询用户信息
func GetUser(db *gorm.DB, userWhere model.User) (user model.User, userErr error) {
	userErr = db.Where(userWhere).First(&user).Error
	return
}

func SetRole(user model.User) (i int64, dbErr error) {
	db := common.GetDB()
	update := db.Model(&user).Select("role", "name", "password").Updates(user)
	i = update.RowsAffected
	dbErr = update.Error
	return
}

func ResetPassword(user model.User) (i int64, dbErr error) {
	db := common.GetDB()
	update := db.Model(&user).Select("password").Updates(user)
	i = update.RowsAffected
	dbErr = update.Error
	return
}
